import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
@Component({
  selector: 'app-stopwatch',
  templateUrl: './stopwatch.component.html',
  styleUrls: ['./stopwatch.component.less']
})
export class StopwatchComponent implements OnInit {

  constructor() { }

  public now: Date;
  public timeShow: any;
  public timeNow: any;
  public timeoutId: any;
  public firstBtnStatus = false;
  public secondBtnStatus = false;
  public hour = 0;
  public minute = 0;
  public second = 0;
  public millisecond = 0;

  onClickBtnStart() {
    this.firstBtnStatus = !this.firstBtnStatus;
    this.secondBtnStatus = true;
    this.timeShow.subscribe(params => {
      this.millisecond = this.millisecond + 1;
      if (this.millisecond >= 100) {
        this.millisecond = 0;
        this.second = this.second + 1;
      }
      if (this.second >= 60) {
        this.second = 0;
        this.minute = this.minute + 1;
      }
      if (this.minute >= 60) {
        this.minute = 0;
        this.hour = this.hour + 1;
      }
    });
  }

  onClickBtnSuspend() {
    this.firstBtnStatus = !this.firstBtnStatus;
    clearTimeout(this.timeoutId);
  }

  onClickBtnStop() {
    this.onClickBtnSuspend();
    this.firstBtnStatus = false;
    this.secondBtnStatus = false;
    this.hour = 0;
    this.minute = 0;
    this.second = 0;
    this.millisecond = 0;
  }

  ngOnInit() {
    this.now = new Date();
    // 实时显示时间
    this.timeShow = Observable.create(observer => {
      this.timeoutId = setInterval(() => {
        observer.next();
      }, 10);
    });

    this.timeNow = Observable.create(observer => {
      setInterval(() => {
        observer.next();
      }, 1000);
    });

    this.timeNow.subscribe(params => this.now = new Date());
  }
}
